# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------

import logging,sys,threading,time

from piHAlibs import (confgetval,lst2lines)
from .corelibs import (startscriptexe)
from .coresetup import (SetupDaemons,
    setupctrl,setupnetctrl,setupsrv,
    startsrv,stopsrv,stopallctrls,
    )
from .coremevtq import (mevtq)
from .decoders import (adddecoder,rmdecoder,addparser,rmparser)
from .rpclcmds import (RPCLocalFunctions)
from .dfeatures import (adddfeature,rmdfeature)
from .features import (addfeature,rmfeature)


logger = logging.getLogger()


def runscript(param):
    if isinstance(param,list):
        script = param[0]
    else:
        script = param
    pscript = confgetval('pimucha.conf','FilesPath','STARTScript','startscript/')
    thefile = pscript + script.lower() + '.scr'
    lines = lst2lines(thefile)
    if not lines:
        return False
    print('Executing %s...' % thefile)
    p = threading.Thread(target=startscriptexe, args=(SetupDaemons['SYSLOGF'],lines,))
    p.__name__ = 'ThreadSTARTscript_' + 'script'
    p.daemon = True
    p.start()
    return True
RPCLocalFunctions.append((runscript,'run'))


AdminCmds = {
    'ADDDFeature':adddfeature,
    'ADDFeature':addfeature,
    'RMDFeature':rmdfeature,
    'RMFeature':rmfeature,
    'ADDDecoder':adddecoder,
    'ADDParser':addparser,
    'MEVTQ':mevtq,
    'RMDecoder':rmdecoder,
    'RMParser':rmparser,
    'SETUPctrl':setupctrl,
    'SETUPnetctrl':setupnetctrl,
    'SETUPsrv':setupsrv,
    'STARTsrv':startsrv,
    'STOPall':stopallctrls,
    'STOPsrv':stopsrv,
    'RUN':runscript,
    }
